{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@riseup.net>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

{-# LANGUAGE OverloadedStrings #-}

module FunBot.Sources.WebListener.Util
    ( refToBranch
    , refToTag
    , nl
    , takeLine
    , uriSpace
    , uriHost
    )
where

import Data.Maybe (fromMaybe)
import Network.URI

import qualified Data.Text as T

refToBranch :: T.Text -> T.Text
refToBranch ref = fromMaybe ref $ T.stripPrefix "refs/heads/" ref

refToTag :: T.Text -> T.Text
refToTag ref = fromMaybe ref $ T.stripPrefix "refs/tags/" ref

nl :: Char -> Bool
nl c = c == '\n' || c == '\r'

takeLine :: T.Text -> T.Text
takeLine = T.takeWhile $ not . nl

uriSpace :: Maybe URI -> T.Text
uriSpace (Just URI { uriPath = _ : p }) = T.pack $ takeWhile (/= '/') p
uriSpace _                              = "UNKNOWN"

uriHost :: Maybe URI -> T.Text
uriHost mu = fromMaybe "UNKNOWN" $ do
    uri <- mu
    auth <- uriAuthority uri
    return $ T.pack $ uriRegName auth
